//
//  EditLearnTagVC.m
//  APP_login
//
//  Created by edz on 7/9/21.
//  Copyright © 2021 baicai. All rights reserved.
//

#import "EditLearnTagVC.h"
#import "CustomHeaderView.h"
#import "CustomCollectionCell.h"
#import "SectionModel.h"
#import "TagModel.h"
#import "SelectTagButton.h"
#import "CustomTagView.h"
#import "InformationModel.h"
#import "BZKTools.h"
#import "Masonry.h"

@interface EditLearnTagVC ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
CustomTagViewDelegent
>

@property (nonatomic, strong) UICollectionView *collect;
@property (nonatomic, strong) UIBarButtonItem *finishButton;
@property (nonatomic, strong) UILabel *selectedCountLable;
@property (nonatomic, strong) UIButton *customTagButton;
@property (nonatomic, strong) NSMutableArray * sectionArray;
@property (nonatomic, strong) UIView *selectedView;
@property (nonatomic, strong) NSMutableArray *selectXValueArray;
@property (nonatomic, strong) NSMutableArray *selectedModelArray;
@property (nonatomic, strong) InformationModel *informationModel;
@end

@implementation EditLearnTagVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _informationModel = [InformationModel new];

    [self selectedCountLableText];
    
    self.navigationItem.title = @"编辑学习标签";
    self.view.backgroundColor = [UIColor whiteColor];
    _selectXValueArray = [[NSMutableArray alloc] init];
    _selectedModelArray = [[NSMutableArray alloc] init];
    
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] init];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    _finishButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finishButtonClick)];
    self.navigationItem.rightBarButtonItem = _finishButton;
    
    _selectedCountLable = [[UILabel alloc] init];
    [self.view addSubview:_selectedCountLable];
    [_selectedCountLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(150, 20));
    }];
    _selectedCountLable.textColor = [UIColor grayColor];
    
    _selectedView = [[UIView alloc] init];
    [self.view addSubview:_selectedView];
    [_selectedView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.left.right.mas_equalTo(20);
        make.height.mas_equalTo(80);
    }];
    
    //创建layout布局类
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置布局方式为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个item的大小
    layout.itemSize = CGSizeMake(115, 40);
    //通过布局layout来创建collectionView
    _collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collect.backgroundColor = [UIColor whiteColor];
    _collect.delegate = self;
    _collect.dataSource = self;
    //注册item类型，使用系统类型
    [_collect registerClass:[CustomCollectionCell class] forCellWithReuseIdentifier:@"cellid"];
    [_collect registerClass:[CustomHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerId"];
    [_collect registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerId"];
    [self.view addSubview:_collect];
    [_collect mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(100);
        make.height.mas_equalTo(410);
    }];
    
    
    _customTagButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:_customTagButton];
    [_customTagButton mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(530);
        make.height.mas_equalTo(50);
    }];
    [_customTagButton setTitle:@"+自定义学习标签" forState:UIControlStateNormal];
    [_customTagButton addTarget:self action:@selector(customTagButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_customTagButton.layer setBorderWidth:1];//设置边界的宽度
    _customTagButton.layer.borderColor=[UIColor colorWithRed:197/255.0f green:224/255.0f blue:254/255.0f alpha:1.0f].CGColor;
    
    //初始化数据
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"section" ofType:@"plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSArray *sectionArry = [dic objectForKey:@"section"];
    _sectionArray = [NSMutableArray array];
    for (NSDictionary *section in sectionArry) {
        SectionModel * sectionModel = [[SectionModel alloc] init];
        sectionModel.henderTitle = [section objectForKey:@"header"];
        sectionModel.tagArray = [[NSMutableArray alloc] init];
        for (NSDictionary *model in [section objectForKey:@"tagModelArray"]) {
            TagModel* tagModel = [[TagModel alloc] init];
            tagModel.tagState =  [(NSNumber*)[model objectForKey:@"tagState"]boolValue];
            tagModel.tagTittle = [model objectForKey:@"tagTitle"];
            [sectionModel.tagArray addObject:tagModel];
        }
        [_sectionArray addObject:sectionModel];
    }
    
}
-(void) setOldArray:(NSMutableArray *)oldArray{
    if (oldArray.count != 0) {
        _selectedModelArray = oldArray;
        [self loadSelectedCell];
        [self importTagLoad];
        [_collect reloadData];
    }
}

- (void) importTagLoad{
    for (int i = 0; i<_selectedModelArray.count; i++) {
        TagModel *model = _selectedModelArray[i];
        for (SectionModel *sectionModel in _sectionArray) {
           [sectionModel.tagArray enumerateObjectsUsingBlock:^(TagModel *tagModel, NSUInteger index, BOOL* stop){
               if ([tagModel.tagTittle isEqualToString:model.tagTittle]) {
                   tagModel.tagState = !tagModel.tagState;
                   *stop = YES;
               }
           }];
        }
    }
    
}

#pragma mark -返回分区个数
//返回分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _sectionArray.count;
}

#pragma mark -返回每个分区item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SectionModel* sectionModel = _sectionArray[section];
    return sectionModel.tagArray.count;
}

#pragma mark -设置每个cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CustomCollectionCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    SectionModel* sectionModel = _sectionArray[indexPath.section];
    if (indexPath.row < sectionModel.tagArray.count) {
        cell.model = sectionModel.tagArray[indexPath.row];
    }
    return cell;
}

#pragma mark -返回头部高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.bounds.size.width, 50);
}
#pragma mark -返回尾部高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(self.view.bounds.size.width, 15);
}
#pragma mark -设置头部尾部视图
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual: UICollectionElementKindSectionHeader]) {
        CustomHeaderView *headerleView =  [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerId" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            headerleView.model = _sectionArray[0];
            [headerleView getTitleColer:[UIColor colorWithRed:60/255.0f green:141/255.0f blue:251/255.0f alpha:1.0f]];
        }
        if (indexPath.section == 1) {
            headerleView.model = _sectionArray[1];
            [headerleView getTitleColer:[UIColor colorWithRed:255/255.0f green:131/255.0f blue:31/255.0f alpha:1.0f]];
        }
        return headerleView;
    }
    if ([kind isEqual: UICollectionElementKindSectionFooter]) {
        UICollectionReusableView *footerView = [_collect dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerId" forIndexPath:indexPath];
        if (footerView == nil) {
            footerView = [[UICollectionReusableView alloc] init];
        }
        footerView.backgroundColor = [UIColor whiteColor];
        return footerView;
    }
    return nil;
}

#pragma mark -返回点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel* section = _sectionArray[indexPath.section];
    TagModel *model = section.tagArray[indexPath.row];
    BOOL value = model.tagState;
    if (!value && _selectXValueArray.count < 3) {
        //修改模型
        model.tagState = !value;
        section.tagArray[indexPath.row] = model;
        //选中模型加入数组
        [_selectedModelArray addObject:model];
        [self loadSelectedCell];
    }
    if (value) {
        model.tagState = !value;
        section.tagArray[indexPath.row] = model;
        [self removeSelectView:model];
    }
    [_collect reloadData];
}

- (BOOL) collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}


#pragma mark -自定义按钮视图的添加
- (void)customTagButtonClick{
    if (_selectXValueArray.count < 3) {
        CustomTagView *customTagView = [[CustomTagView alloc] init];
        [customTagView showView:[self getKeyWindow]];
        [customTagView mas_makeConstraints:^(MASConstraintMaker *make){
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
        }];
        customTagView.delegent = self;
    }
}

- (void)customTagViewDelegentGetTagTitle:(NSString *)title{
    if (title.length >0 ) {
        TagModel *tagModel = [[TagModel alloc] init];
        tagModel.tagState = YES;
        tagModel.tagTittle = title;
        [_selectedModelArray addObject: tagModel];
        [self addSelectView:tagModel];
    }
}
#pragma mark -刷新UI
-(void) loadSelectedCell{
    //刷新ui
    for (NSInteger i = _selectXValueArray.count; i < _selectedModelArray.count; i++) {
        [self addSelectView:_selectedModelArray[i]];
    }
    [self selectedCountLableText];
}

- (void)addSelectView:(TagModel*)model{
    SelectTagButton *tagButton = [SelectTagButton buttonWithType:UIButtonTypeSystem];
    [_selectedView addSubview:tagButton];
    tagButton.model = model;
    CGFloat width = [self stringWidth:model.tagTittle];
    if (_selectXValueArray.count == 0 ) {
        tagButton.frame = CGRectMake(0, 10, 14+width, 25);
        NSInteger nextXValue = tagButton.frame.size.width+5;
        NSNumber *xValue = [NSNumber numberWithInteger:nextXValue];
        [_selectXValueArray addObject:xValue];
    }else{
        NSInteger x = [_selectXValueArray[_selectXValueArray.count-1] intValue];
        tagButton.frame = CGRectMake(x, 10, 14+width, 25);
        NSInteger nextXValue = tagButton.frame.origin.x +tagButton.frame.size.width+5;
        NSNumber *xValue = [NSNumber numberWithInteger:nextXValue];
        [_selectXValueArray addObject:xValue];
    }
    [tagButton addTarget:self action:@selector(tagButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void) tagButtonClick:(UIButton*) button{
    for (SectionModel *sectionModel in _sectionArray) {
        [sectionModel.tagArray enumerateObjectsUsingBlock:^(TagModel *tagModel, NSUInteger index, BOOL* stop){
            if ([tagModel.tagTittle isEqualToString:button.titleLabel.text]) {
                tagModel.tagState = !tagModel.tagState;
                *stop = YES;
            }
        }];
     }
     TagModel *model;
     for (TagModel *tagModel in _selectedModelArray) {
         if ([tagModel.tagTittle isEqualToString:button.titleLabel.text]) {
             model = tagModel;
             break;
         }
     }
     [self removeSelectView:model];
     [_collect reloadData];
}
#pragma mark -重新布局UI
- (void) removeSelectView:(TagModel*) mode{
    int index = 0;
    for (int i = 0; i<_selectedModelArray.count; i++) {
        TagModel *tagModel =_selectedModelArray[i];
        if ([mode.tagTittle isEqualToString :tagModel.tagTittle ]) {
            index = i;
            break;
        }
    }
    for (int i = index+1; i <_selectedModelArray.count ; i++) {
        CGFloat viewXValue = _selectedView.subviews[i].frame.origin.x;
        CGFloat willRemoveViewXValue = _selectedView.subviews[index].frame.size.width;
        CGFloat viewYValue = _selectedView.subviews[i].frame.origin.y;
        CGFloat viewWidth = _selectedView.subviews[i].frame.size.width;
        CGFloat viewHeight = _selectedView.subviews[i].frame.size.height;
        _selectedView.subviews[i].frame = CGRectMake(viewXValue - willRemoveViewXValue-5, viewYValue, viewWidth, viewHeight);
        NSInteger changeXValue = viewWidth + _selectedView.subviews[i].frame.origin.x+5;
        _selectXValueArray[i] = [NSNumber numberWithInteger:changeXValue];
    }
    [_selectedView.subviews[index] removeFromSuperview];
    [_selectedModelArray removeObject:_selectedModelArray[index]];
    [_selectXValueArray removeObject:_selectXValueArray[index]];
    [self selectedCountLable];
}
#pragma mark -计算字符串宽度x
-(CGFloat)stringWidth:(NSString*)str{
    return [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width;
}
#pragma mark -完成点击
- (void)finishButtonClick{
    [self.delegate editLearnTagVCSetNewTagArray:_selectedModelArray];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -动态标题
-(void)selectedCountLableText{
    _selectedCountLable.text = [NSString stringWithFormat:@"已选学习标签(%ld/3)",_selectedModelArray.count];
}

- (UIWindow*)getKeyWindow{
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        if (window.isKeyWindow) {
            return window;
        }
    }
    return nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
